package com.plugin.dingding;

import lombok.extern.log4j.Log4j2;
import org.apache.commons.codec.cli.Digest;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import sun.security.provider.MD5;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@RestController
@RequestMapping("/mucapi")
@CrossOrigin
@Log4j2
public class MucPlgApiController {
    private String ak = "ffb089dabca34f318a7cd102bb7330ac";
    private String sk = "5f0dfccf0ca69430e4083dc6ffff35e35b0b148e8030d55bdfc8104a7eeaf9e3";


    @GetMapping("/req")
    public AjaxRet req(String name){
        String timestamp = String.valueOf(new Date().getTime());
        Clog.l(timestamp);
        String token = DigestUtils.md5DigestAsHex((ak + sk+ timestamp).getBytes());

        //post请求 POST http://47.114.131.229:8082/function/sync/1768782122328645633
        String url = "http://47.114.131.229:8082/function/sync/1768782122328645633";
        Map<String,Object> params = new HashMap<>();
        params.put("string1",name);
        params.put("appKey",ak);
        params.put("token",token);
        params.put("timestamp",timestamp);
        LinkedHashMap ret = sendRemoteRequest(url,"post",params);
        Clog.l(ret);
        return AjaxRet.success(ret);
    }

    public static LinkedHashMap sendRemoteRequest(String url, String requestMethod, Map<String, Object> params) {
        RestTemplate client = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        HttpMethod method = null;
        //将请求头部和参数合成一个请求
        HttpEntity<Map<String, Object>> requestEntity = null;
        //执行HTTP请求，将返回的结构使用BaseResponse类格式化
        ResponseEntity<Object> response = null;
        //get请求
        if (requestMethod.equalsIgnoreCase("get")) {
            method = HttpMethod.GET;
            requestEntity = new HttpEntity<>(null, headers);
            response = client.exchange(url, method, requestEntity, Object.class, params);
            //post请求
        } else if (requestMethod.equalsIgnoreCase("post")) {
            method = HttpMethod.POST;
            requestEntity = new HttpEntity<>(params, headers);
            response = client.exchange(url, method, requestEntity, Object.class);
        }
        return (LinkedHashMap) response.getBody();
    }

}
